﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using SdmxMl.Structure;
using SdmxMl.Panels;


namespace SdmxMl.UC
{
    public partial class UcContactType : UserControl
    {
        private OrganisationType org = null;

        private UcMlText ucMlName = null;
        private UcMlText ucMlDept = null;
        private UcMlText ucMlRole = null;
        private ContactInfo info;
        private DataTable infoTable;

        private TreeNode maintenanceNode;
        private TreeNode collectorNode;
        private TreeNode disseminatorNode;
        private TreeNode reporterNode;
        private TreeNode othersNode;
        private bool isFinal;

        public UcContactType()
        {
            InitializeComponent();
            ucMlName = new UcMlText();
            customComboBoxName.DropDownControl = ucMlName;

            ucMlDept = new UcMlText();
            customComboBoxDept.DropDownControl = ucMlDept;

            ucMlRole = new UcMlText();
            customComboBoxRole.DropDownControl = ucMlRole;


            maintenanceNode = treeViewContact.Nodes[0].Nodes["NodeMaintenance"].Nodes[0];
            collectorNode   = treeViewContact.Nodes[0].Nodes["NodeCollector"].Nodes[0];
            disseminatorNode= treeViewContact.Nodes[0].Nodes["NodeDisseminator"].Nodes[0];
            reporterNode    = treeViewContact.Nodes[0].Nodes["NodeReporter"].Nodes[0];
            othersNode = treeViewContact.Nodes[0].Nodes["NodeOthers"];
        }


        public void BindFromNode(OrganisationType org, bool isFinal)
        {
            this.isFinal = isFinal;
            this.org = org;
            BindToControls();
            IsFinalEditControls(isFinal);
        }

        public bool UpdateNodeTag()
        {
            if (org != null)
            {
                // Refresh currently edited
                treeViewContact_BeforeSelect(this, new TreeViewCancelEventArgs(treeViewContact.SelectedNode, false, TreeViewAction.Unknown));

                // Attach other list
                org.OtherContactList.Clear();
                foreach (TreeNode n in othersNode.Nodes)
                {
                    ContactType ct = n.Tag as ContactType;
                    if (ct != null)
                        org.OtherContactList.Add(ct);
                }
            }
            return false; // true on error
        }

        // No edition if Parent Artefact IsFinal
        private void IsFinalEditControls(bool isFinal)
        {
            textBoxId.ReadOnly = isFinal;
            customComboBoxName.IsFinal = isFinal;
            customComboBoxDept.IsFinal = isFinal;
            customComboBoxRole.IsFinal = isFinal;
            buttonRemoveOther.Enabled = buttonNewOther.Enabled = isFinal == false;
        }

        private void UpdateDetail(ContactType ct)
        {
            if (ct != null)
            {
                textBoxId.Text = ct.Id;
                customComboBoxName.Text = ct.Name.ToString(); ;
                ucMlName.ML = ct.Name;
                customComboBoxDept.Text = ct.Department.ToString(); ;
                ucMlDept.ML = ct.Department;
                customComboBoxRole.Text = ct.Role.ToString(); ;
                ucMlRole.ML = ct.Role;
            }
        }

        private void UpdateContact(ContactType ct, TreeNode curNode)
        {
            if (ct != null)
            {
                ct.Id = textBoxId.Text;
                ct.Name.UpdateForCurrentLanguage(customComboBoxName.Text);
                ct.Department.UpdateForCurrentLanguage(customComboBoxDept.Text);
                ct.Role.UpdateForCurrentLanguage(customComboBoxRole.Text);

                TreeNode ndSel = null;
                InitNode(curNode, ct, ref ndSel);
            }
        }


        private void InitNode(TreeNode n, ContactType ct, ref TreeNode ndSel)
        {
            n.Tag = ct;
            n.ImageIndex = n.SelectedImageIndex = ct.Name.IsEmpty ? 3 : 2;
            n.Text = ct.ToString();
            if (ct.Name.IsEmpty == false)
            {
                if (ndSel == null)
                    ndSel = n;
                if (n.Parent != null)
                    n.Parent.Expand();
            }
        }


        private void BindToControls()
        {
            treeViewContact.SelectedNode = null;
            maintenanceNode.Tag = null;
            collectorNode.Tag = null;
            disseminatorNode.Tag = null;
            reporterNode.Tag = null;
            othersNode.Nodes.Clear();

            if (org == null)
            {
                Visible = false;
            }
            else
            {
                treeViewContact.BeginUpdate();

                treeViewContact.CollapseAll();
                treeViewContact.Nodes[0].Expand();
                TreeNode nodeToSelect = null;
                Visible = true;
                InitNode(maintenanceNode, org.MaintenanceContact, ref nodeToSelect);
                InitNode(collectorNode, org.CollectorContact, ref nodeToSelect);
                InitNode(disseminatorNode, org.DisseminatorContact, ref nodeToSelect);
                InitNode(reporterNode, org.ReporterContact, ref nodeToSelect);

                foreach (ContactType ct in org.OtherContactList)
                {
                    TreeNode n = new TreeNode();
                    InitNode(n, ct, ref nodeToSelect);
                    othersNode.Nodes.Add(n);
                }

                treeViewContact.SelectedNode = nodeToSelect == null ? maintenanceNode : nodeToSelect;
                // If panel hideden, event not run so call update manually
                UpdateDetailPane(nodeToSelect);


                treeViewContact.EndUpdate();

            }
        }

        //Create a new other contact
        private void buttonNewOther_Click(object sender, EventArgs e)
        {
            ContactType newOtherContact = new ContactType();
            newOtherContact.Name.UpdateForCurrentLanguage("Undefined");
            org.OtherContactList.Add(newOtherContact);
            TreeNode node = new TreeNode(newOtherContact.ToString());
            othersNode.Nodes.Add(node);
            node.Tag = newOtherContact;
            treeViewContact.SelectedNode = node;
        }

        private void buttonRemove_Click(object sender, EventArgs e)
        {
            if (treeViewContact.SelectedNode.Parent == othersNode)
            {
                ContactType c = treeViewContact.SelectedNode.Tag as ContactType;
                if (c != null)
                {
                    TreeNode targetNode = treeViewContact.SelectedNode;
                    treeViewContact.SelectedNode = othersNode;
                    org.OtherContactList.Remove(c);
                    othersNode.Nodes.Remove(targetNode);
                    if (othersNode.Nodes.Count > 0)
                        treeViewContact.SelectedNode = othersNode.LastNode;

                }
            }   
        }

        private void treeViewContact_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            if (treeViewContact.SelectedNode != null )
            {
                ContactType ct = treeViewContact.SelectedNode.Tag as ContactType;
                if (ct != null)
                    UpdateContact(ct, treeViewContact.SelectedNode);
            }

        }

        private void treeViewContact_AfterSelect(object sender, TreeViewEventArgs e)
        {
            UpdateDetailPane(e.Node);
            buttonRemoveOther.Enabled = othersNode.Nodes.Count > 0 && !isFinal;
        }

        private void UpdateDetailPane(TreeNode node)
        {
            if (node != null)
            {
                ContactType ct = node.Tag as ContactType;
                panelDetailContact.Visible = ct != null;
                if (ct != null)
                {
                    UpdateDetail(ct);
                    UpdateDataGrid(ct.ContactInfo);

                }
            }

        }


        #region Datagrid

        private void SetGridTextWidth()
        {
            // dataGridViewInfo.Columns[2].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            //  dataGridViewInfo.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

        /// <summary>Update Grid buttons state</summary>
        /// <param name="enable">If true buttons are enabled</param>
        protected void EnableGrigButtons(bool enable)
        {
            if (isFinal)
                enable = false;

            butAdd.Enabled = enable;
            butEdit.Enabled = enable && infoTable.Rows.Count > 0;
            butRemove.Enabled = enable && infoTable.Rows.Count > 0  && dataGridViewInfo.SelectedCells.Count > 0;
        }

       
        private void UpdateDataGrid(ContactInfo info)
        {
            this.info = info;
            if (info != null)
            {
                infoTable = info.AsDataTable();
                dataGridViewInfo.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders;
                dataGridViewInfo.DataSource = infoTable;
                SetGridTextWidth();
                EnableGrigButtons(true);

            }
            else
            {
                dataGridViewInfo.DataSource = null;
                infoTable = null;
                EnableGrigButtons(false);
            }

        }

        private void butEdit_Click(object sender, EventArgs e)
        {
            int rowIndex = 0;
            if (dataGridViewInfo.SelectedCells.Count > 0)
                rowIndex = dataGridViewInfo.SelectedCells[0].RowIndex;

            if (rowIndex < infoTable.Rows.Count)
            {
                DlgEditContactInfo aDlg = new DlgEditContactInfo();
                aDlg.BindRow(infoTable.Rows[rowIndex]);

                if (aDlg.ShowDialog(this) == DialogResult.OK)
                {
                    info.FromDataTable(infoTable);
                }
            }
        }

        private void butAdd_Click(object sender, EventArgs e)
        {
            infoTable.Rows.Add(new object[] { "Undefined", "", "", "", "" });
            EnableGrigButtons(true);
            dataGridViewInfo.ClearSelection();
            dataGridViewInfo.Rows[dataGridViewInfo.Rows.Count - 1].Cells[0].Selected = true;

        }

        private void butRemove_Click(object sender, EventArgs e)
        {
            int rowIndex = 0;
            if (dataGridViewInfo.SelectedCells.Count > 0)
            {
                rowIndex = dataGridViewInfo.SelectedCells[0].RowIndex;
                if (infoTable.Rows.Count > rowIndex)
                {
                    infoTable.Rows.RemoveAt(rowIndex);
                    info.FromDataTable(infoTable);
                    EnableGrigButtons(true);
                }
            }
        }

        private void dataGridViewInfo_SelectionChanged(object sender, EventArgs e)
        {
            EnableGrigButtons(true);
        }

        #endregion //Datagrid

    }
}
